@echo off

rem AdxAdmin folders creation
rem 
set "SRVUSER=%~1"
@echo Parameters receiving %SRVUSER% ...
rem For local account, we remove the .\
if defined SRVUSER (
  IF "%SRVUSER:~0,2%"==".\" (
    set "SRVUSER=%SRVUSER:~2%"
  )
)

@echo Folders creation in ${INSTALL_PATH} ...
IF NOT EXIST "${INSTALL_PATH}${FILE_SEPARATOR}adxd" mkdir "${INSTALL_PATH}${FILE_SEPARATOR}adxd"
IF NOT EXIST "${INSTALL_PATH}${FILE_SEPARATOR}adxdlog" mkdir "${INSTALL_PATH}${FILE_SEPARATOR}adxdlog"
IF NOT EXIST "${INSTALL_PATH}${FILE_SEPARATOR}adxdtra" mkdir "${INSTALL_PATH}${FILE_SEPARATOR}adxdtra"
IF NOT EXIST "${INSTALL_PATH}${FILE_SEPARATOR}bin" mkdir "${INSTALL_PATH}${FILE_SEPARATOR}bin"
IF NOT EXIST "${INSTALL_PATH}${FILE_SEPARATOR}ebin" mkdir "${INSTALL_PATH}${FILE_SEPARATOR}ebin"
IF NOT EXIST "${INSTALL_PATH}${FILE_SEPARATOR}inst" mkdir "${INSTALL_PATH}${FILE_SEPARATOR}inst"
IF NOT EXIST "${INSTALL_PATH}${FILE_SEPARATOR}lan" mkdir "${INSTALL_PATH}${FILE_SEPARATOR}lan"
IF NOT EXIST "${INSTALL_PATH}${FILE_SEPARATOR}tmp" mkdir "${INSTALL_PATH}${FILE_SEPARATOR}tmp"

set ADXADM=C:\Sage
@echo Administration path initialization in %ADXADM% ...
IF NOT EXIST "%ADXADM%" mkdir "%ADXADM%"
echo ${INSTALL_PATH} > "%ADXADM%\adxadm"

if defined SRVUSER (
  @echo Rights setting for %SRVUSER% ...
  IF NOT "%SRVUSER%"=="localsystem" icacls "${INSTALL_PATH}" /t /c /q /grant %SRVUSER%:rx
  IF NOT "%SRVUSER%"=="localsystem" icacls "%ADXADM%\adxadm" /t /c /q /grant %SRVUSER%:rx
)
@echo off

rem AdxAdmin service creation
rem 

rem Input parameter 1 : SRVUSER is the account name that will launch the ADXADMIN service (Domain\DomainAccount or .\LocalAccount)
rem Input parameter 2 : SRVPASS is the account password of the account name
set "SRVUSER=%~1"
set "SRVPASS=%~2"

rem create service name
set INSTALL_PATH=${INSTALL_PATH}
set LOGPATH=${INSTALL_PATH}${FILE_SEPARATOR}adxdlog
set EXPANDED_SERVICE_NAME=${UNINSTALL_NAME}
set SERVICE_NAME=%EXPANDED_SERVICE_NAME: =_%

set NEW_SERVICE_DISPLAYNAME=${service.name}
set NEW_SERVICE_DESCRIPTION=${service.description}

rem "%SRVUSER%" == "" : we are in Administrator mode 
if NOT defined SRVUSER (
    @echo Service creation in Administrator mode...
    sc.exe create %SERVICE_NAME% binpath= "%INSTALL_PATH%\bin\adxdsrv.exe -r Adonix/X3RUNTIME/ADXADMIN -v -s ${adxadmin.service.port} -e FRA" DisplayName= "%NEW_SERVICE_DISPLAYNAME%"  start= auto type= own
) else (
  IF "%SRVUSER%" == ".\localsystem" (
    @echo Service creation with localsystem...
    sc.exe create %SERVICE_NAME% binpath= "%INSTALL_PATH%\bin\adxdsrv.exe -r Adonix/X3RUNTIME/ADXADMIN -v -s ${adxadmin.service.port} -e FRA" DisplayName= "%NEW_SERVICE_DISPLAYNAME%"  start= auto type= own
  ) else (
    @echo Service creation with user %SRVUSER%...
    sc.exe create %SERVICE_NAME% binpath= "%INSTALL_PATH%\bin\adxdsrv.exe -r Adonix/X3RUNTIME/ADXADMIN -v -s ${adxadmin.service.port} -e FRA" DisplayName= "%NEW_SERVICE_DISPLAYNAME%"  start= auto type= own obj= "%SRVUSER%" password= "%SRVPASS%"
  )
)

REM Set Service description
sc description %SERVICE_NAME% "%NEW_SERVICE_DESCRIPTION%"
REM Set the service recovery options
sc failure %SERVICE_NAME% reset=0 actions=restart/60000/restart/60000/none/0
@echo off

rem AdxAdmin service deletion
rem 

@echo Service deletion ...

set EXPANDED_SERVICE_NAME=${UNINSTALL_NAME}
set SERVICE_NAME=%EXPANDED_SERVICE_NAME: =_%

sc.exe delete %SERVICE_NAME%@echo off

rem AdxAdmin service deletion
REM Call a Powershell script to check XML adxInstall.xml
REM if this XML is not empty, do not delete the service 

@echo Service deletion ...
Powershell.exe -executionpolicy remotesigned -File  "${INSTALL_PATH}${FILE_SEPARATOR}servicedelete.uninstall.ps1" -servicename  "Sage_Safe_X3_AdxAdmin"

@IF %ERRORLEVEL% EQU 0 GOTO NOERROR1
echo An error occured while launching servicedelete.ps1 - Error %ERRORLEVEL%
REM EXIT %ERRORLEVEL%
:NOERROR1
exit 0
#Requires -RunAsAdministrator
#
<# ###########################################################
# servicdelete.ps1
# X3 V12 - PowerShell Script to check and delete AdxAdmin Service
#
# Check file ADXADMIN/inst/adxinstalls.xml 
# ex: C:\Sage\SafeX3\ADXADMIN\inst\adxinstalls.xml

# INPUT PARAMTERS : 1 mandatory
#   Parameter 1 : -servicename"
#   Parameter 2 : -xmlfile"
# ex:
# Powershell.exe -executionpolicy remotesigned -File  .\servicedelete.ps1 -servicename "Sage X3 AdxAdmin" -xmlfile "../inst/adxinstalls.xml"
###########################################################>

# Read Xml file ADXADMIN/inst/adxinstall.xml

# <?xml version="1.0" encoding="utf-8" standalone="no"?>
# <install>
# <module family="RUNTIME" name="LOCAL95" type="MAIN">
# <component.runtime.installstatus>update</component.runtime.installstatus>
# <component.runtime.name>LOCAL95</component.runtime.name>
# <component.runtime.path>c:\Sage\LOCAL95\runtime</component.runtime.path>
# <component.runtime.platform>WIN64</component.runtime.platform>
# <component.runtime.servername>frpo402328.sagefr.adinternal.com</component.runtime.servername>
# <component.runtime.version>R096.001.00183</component.runtime.version>
# <runtime.adxd.adxdlog>
#     </runtime.adxd.adxdlog>
# <runtime.adxd.adxdtra>
#     </runtime.adxd.adxdtra>
# <runtime.adxd.adxlan>fra</runtime.adxd.adxlan>
# <runtime.adxd.adxport>20130</runtime.adxd.adxport>
# <runtime.adxd.adxserialpath>
#     </runtime.adxd.adxserialpath>
# <runtime.adxd.adxstatus>
#     </runtime.adxd.adxstatus>
# <runtime.adxd.adxtra>
#     </runtime.adxd.adxtra>
# <runtime.connection.hostnameincert>
#     </runtime.connection.hostnameincert>
# <runtime.connection.odbcencrypt>Yes</runtime.connection.odbcencrypt>
# <runtime.connection.trustservercertificate>Yes</runtime.connection.trustservercertificate>
# <runtime.http.hostnamepublic>
#     </runtime.http.hostnamepublic>
# <runtime.http.portpublic>
#     </runtime.http.portpublic>
# <runtime.login.adxservicepwd>CRYPT:vfrw3QnsalTo2rrtccqkqeSpxo2vkXvaUcc</runtime.login.adxservicepwd>
# <runtime.login.adxserviceusr>sagefr\frdepo</runtime.login.adxserviceusr>
# <runtime.odbc.dbhome>
#     </runtime.odbc.dbhome>
# <runtime.odbc.dblink>
#     </runtime.odbc.dblink>
# <runtime.odbc.forcedblink>False</runtime.odbc.forcedblink>
# <runtime.odbc.tools>
#     </runtime.odbc.tools>
# <runtime.powershell.path>C:\Program Files\PowerShell\7\pwsh.exe</runtime.powershell.path>
# <runtime.system.adxcacheenabled>
#     </runtime.system.adxcacheenabled>
# <runtime.system.atxinddisabled>
#     </runtime.system.atxinddisabled>
# <runtime.system.fdecachedisabled>
#     </runtime.system.fdecachedisabled>
# <runtime.system.lowperformance>true</runtime.system.lowperformance>
# </module>
# </install>


param(
    [Parameter(ParameterSetName = "-servicename", Mandatory = $false, HelpMessage = "delete AdxAdmin service 'Sage_Safe_X3_AdxAdmin'")] [string]$servicename,
    [Parameter(ParameterSetName = "-xmlfile", Mandatory = $false, HelpMessage = "Xml file path 'adxinstalls.xml'")] [string]$xmlfile
)


function Get-Formatted-Date() {
    <#
        .SYNOPSIS
            Date formating for Log trace
        .INPUTS
            None
        .OUTPUTS
            Date in a specific Format, such as  2020_09_28_08_36_59_123
    #>
    return Get-Date -Format yyyy_MM_dd_HH_mm_ss_fff
}

function Show-Usage() {
    Add-To-Log -line "Usage: servicedelete.ps1 -servicename [Sage_Safe_X3_AdxAdmin]" -file $SCRIPT_LOGDAT -errorLevel 0
}

function Add-To-Log {
    <#
        .SYNOPSIS 
            Log routine that will accept an input line, log it to a file and indicate if the line 
            represents an error or not. 
        .INPUTS
            line: Some type of sentence describing what you want to log to the log file
            file: The file you want to append the sentence to
        .OUTPUTS
            None
    #>
    param(
        [Parameter(Mandatory = $true, Position = 1)] [string] $line,
        [Parameter(Mandatory = $true, Position = 2)] [string] $file,
        [Parameter(Mandatory = $true, Position = 3)] [int] $errorLevel
    )

    # Beautification of the log
    if ($errorLevel -eq 1) {
        Add-Content -Value (("-" * 40) + "Error Start" + ("-" * 40)) -Path $SCRIPT_LOGDAT 
    } 
    
    Add-Content -Value $line -Path $file
    Write-Host $line

    # Beautification of the log
    if ($errorLevel -eq 2) {
        Add-Content -Value (("-" * 40) + "Error End" + ("-" * 42)) -Path $SCRIPT_LOGDAT
    }    
}


<###########################################################
#   MAIN SCRIPT ENTRY POINT                               #
###########################################################>

$defaultServiceName = "Sage_Safe_X3_AdxAdmin"
if ($isLinux) {
    $defaultServiceName = "sage_x3_adxadmin.service"
}

try {

    $LOGDAT = Get-Formatted-Date
    $SCRIPT_LOG_BASE = (Get-Item $PSCommandPath).BaseName    	
    $SCRIPT_LOGDAT = Join-Path -Path  ([System.IO.Path]::GetTempPath()) -ChildPath  "$SCRIPT_LOG_BASE-$LOGDAT.log"
    Write-Host "Log file generated will be: $SCRIPT_LOGDAT - Please analyze content after process !"
    Set-Content -Value "Start of $SCRIPT_LOG_BASE " -Path $SCRIPT_LOGDAT 
    Add-To-Log -line "Initializations..." -file $SCRIPT_LOGDAT -errorLevel 0

    if ([string]::IsNullOrEmpty($servicename)) {
        $servicename = $defaultServiceName #  "Sage_Safe_X3_AdxAdmin", "Sage X3 AdxAdmin"
    }

    $xmlAdxInstall = $xmlfile
    if ([string]::IsNullOrEmpty($xmlAdxInstall)) {
        $xmlAdxInstall = (Get-Item $PSCommandPath).DirectoryName  | Join-Path -ChildPath "inst" | Join-Path -ChildPath "adxinstalls.xml"
    }

    Add-To-Log -line "Read xmlFile $xmlAdxInstall" -file $SCRIPT_LOGDAT -errorLevel 0
    $okToDelete = $false
    if (Test-Path -Path $xmlAdxInstall) {
        [xml]$XmlDocument = Get-Content -Path $xmlAdxInstall
        $xmlElements = Select-Xml -Xml $XmlDocument -XPath "/install/module"  | ForEach-Object { $_.node }
       
        if (($xmlElements -is [Array]) -and ($xmlElements.length -gt 0 )) {
            Add-To-Log -line "Cannot delete service '$servicename'. Elements still present in $xmlAdxInstall" -file $SCRIPT_LOGDAT -errorLevel 1
        }
        else {
            $okToDelete = $true
        }
    }
    else {
        Add-To-Log -line "$xmlAdxInstall not found" -file $SCRIPT_LOGDAT -errorLevel 0
        $okToDelete = $true
    }
    
    if ($okToDelete) {
        Add-To-Log -line "Deleting service '$servicename'" -file $SCRIPT_LOGDAT -errorLevel 0
        
        if ($isLinux) {
            # systemctl disable sage_x3_adxadmin
            # rm -f /etc/systemd/system/sage_x3_adxadmin.service
            # systemctl daemon-reload

            $proc = Start-Process -Wait -PassThru -NoNewWindow -WorkingDirectory "$((Get-Item $PSCommandPath).DirectoryName)" -FilePath "systemctl" -ArgumentList "disable $servicename" -ErrorAction SilentlyContinue
            $proc.WaitForExit()
            $proc.HasExited | out-null #  workaround to avoid $null value 
            Remove-Item -Path "/etc/systemd/system/$servicename"
            $proc = Start-Process -Wait -PassThru -NoNewWindow -WorkingDirectory "$((Get-Item $PSCommandPath).DirectoryName)" -FilePath "systemctl" -ArgumentList "daemon-reload" -ErrorAction SilentlyContinue
            $proc.WaitForExit()
            $proc.HasExited | out-null #  workaround to avoid $null value             
            Add-To-Log -line "Service $servicename deleted" -file $SCRIPT_LOGDAT -errorLevel 0    
        }
        else {
            $service = Get-Service -Name $servicename  # Get-Service -Name $servicename
            if ($service) {
                Stop-Service -Name "$servicename" -ErrorAction SilentlyContinue
                # Remove-Service -Name $servicename =>  this function has been created in pwsh >= V6.0
                # Get-Service -DisplayName "$servicename" | Remove-Service
                $proc = Start-Process -Wait -PassThru -NoNewWindow -WorkingDirectory "$((Get-Item $PSCommandPath).DirectoryName)" -FilePath "sc" -ArgumentList "delete $servicename" -ErrorAction SilentlyContinue
                $proc.WaitForExit()
                $proc.HasExited | out-null #  workaround to avoid $null value             
				 
                Add-To-Log -line "Service $servicename deleted" -file $SCRIPT_LOGDAT -errorLevel 0    
            }
            else {
                Add-To-Log -line "Service '$servicename' not found. Skip deletion procedure" -file $SCRIPT_LOGDAT -errorLevel 0    
            }
        }
    }

}
catch {

    if ($null -ne $SCRIPT_LOGDAT) {
        Add-To-Log -line ($Error[0] | Out-String) -file $SCRIPT_LOGDAT -errorLevel 1
        Add-To-Log -line "Stack Trace: " -file $SCRIPT_LOGDAT -errorLevel 0
        Add-To-Log -line ($PSItem.ScriptStackTrace | Out-String) -file $SCRIPT_LOGDAT -errorLevel 0
        Add-To-Log -line " " -file $SCRIPT_LOGDAT -errorLevel 2
    }
    else {
        throw $Error[0]
    }
    $Error.Clear()
}@echo off

rem AdxAdmin service start
rem 

@echo Service start ...

set EXPANDED_SERVICE_NAME=${UNINSTALL_NAME}
set SERVICE_NAME=%EXPANDED_SERVICE_NAME: =_%

sc.exe start %SERVICE_NAME%@echo off

rem AdxAdmin service stop
rem 

@echo Service stop ...

set EXPANDED_SERVICE_NAME=${UNINSTALL_NAME}
set SERVICE_NAME=%EXPANDED_SERVICE_NAME: =_%

sc.exe stop %SERVICE_NAME%<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<html>
    <br/>
        <center><b>Pré-requis pour le runtime SAFE X3</b></center>
    <br/>
        Vérifiez que vous avez installé les éléments pré-requis suivants avant de poursuivre:
    <br/><br/>
    <ul>
        <li>Microsoft PowerShell <b>version 7.2 minimum</b>.</li>
    </ul>
    <br/>
        Veuillez vous référer à la <b><a href=https://online-help.sageerpx3.com/erp/12/public/index.html>documentation relative aux pré-requis SAFE X3</a></b> pour plus d'informations sur le téléchargement et l'installation de Microsoft PowerShell et des autres pré-requis SAFE X3.
    <br/>
</html><head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<html>
    <br/>
        <center><b>Prerequisites for the SAFE X3 runtime</b></center>
    <br/>
        Make sure you have installed the following prerequisites before processing:
    <br/><br/>
    <ul>
        <li>Microsoft PowerShell <b>version 7.2</b></li>
    </ul>
    <br/>
        Please review the <b><a href=https://online-help.sageerpx3.com/erp/12/public/index.html>prerequisites documentation</a></b> for more details on how to download and install Microsoft PowerShell and other prerequisites for SAFE X3.
    <br/>
</html>